;
(function () {
  'use strict';

  angular.module('services.userBehaviorAnalysis.userChurnAnalysis')
    .service('dUserChurnAnalysisService', dUserChurnAnalysisService);

  function dUserChurnAnalysisService($http, $filter, CoreService, $timeout, CoreLoading) {

    var time = new Date();
    var date = new Date(time.getFullYear(), time.getMonth(), time.getDate() - 61);  //默认当前日期的前2个月

    //页面参数
    this.params = {
      startTime: date,
      endTime: date,
      dimension: 't'
    };

    this.showSearchPanel = true;//显示查询面板
    this.arrow = false;
    this.dimensionType = 't';   //时间维度控制
    this.showIcon = true;   //控制显示折线和表格的图标
    this.showDataByHourBtn = false;   //控制是否显示按时刻展示数据的变量
    this.viewType = 'chart';//默认折线视图类型
    this.showPie = false;  //默认不显示饼图
    this.title = null;  //图表显示的标题
    this.tabTitle=null;
    var chart = null;   //折线图
    var chartByPro_Bl = null;
    var pieByPro_Bl = null;
    var dayCount = 0; //保存查询数据的总天数
    var dataList = [];   //临时数据集合
    var that = this;
    var param = {}; //临时参数对象

    /**
     * 隐藏查询面板
     */
    this.hideSearchPanel = function () {
      this.showSearchPanel = false;
    };

    /**
     * 清空页面旧值
     */
    this.reset = function () {
      that.arrow = false;
      that.dataList = [];
      that.businessLineList = [];
      that.businessLineNames = [];
      that.provincialCompanyList = [];
      that.provinceNames = [];
      that.params.startTime = date;
      that.params.endTime = date;
      that.params.dimension = 't';
      that.viewType = 'chart';
      that.showIcon = false;
      that.showSearchPanel = true;
      that.dimensionType = 't';
      that.showPie = false;
      that.chartByPro_Bl = null;
      that.pieByPro_Bl = null;
      that.tabTitle=null;
      that.title=null;
    };

    //业务线 省份 根据Code获取Name,图表展示标题所需
    this.businessLineList = [];
    this.businessLineNames = [];
    this.provincialCompanyList = [];
    this.provinceNames = [];

    this.selectBL_Provinces = function () {
      //获取业务线
      $http.get('/sas/common/businessLineQuery')
        .then(function (res) {
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            that.businessLineList = res.data.data;
            angular.forEach(that.businessLineList, function (obj) {
              that.businessLineNames.push(obj.businessLineName);
            });
            //获取省公司
            $http.get('/sas/common/provinceQuery')
              .then(function (res) {
                if (res.data.state === '10000' && res.data.data.length >= 1) {
                  that.provincialCompanyList = res.data.data;
                  angular.forEach(that.provincialCompanyList, function (obj) {
                    that.provinceNames.push(obj.provinceName);
                  });
                  that.search();
                } else {
                  CoreService.dialog('查询无数据');
                }
              });
          }
          ;
        });
    };

    /**
     * 查询 通过告警返回码分析判断业务故障
     */
    this.sendData = null;
    this.search = function () {
      that.dataList = [];
      //收起查询面板
      if (!that.showSearchPanel) {
        that.showSearchPanel = true;
        return;
      }
      //时间粒度为天时，最多只能查询60天的数据
      var endTime = that.params.endTime.getTime();
      var startTime = that.params.startTime.getTime();
      dayCount = (endTime - startTime) / 1000 / 60 / 60 / 24;
      if (dayCount > 59) {
        CoreService.dialog('只能查询60天内的数据！');
        return;
      }

      //copy页面参数 格式化参数
      param = angular.copy(that.params);
      param.startTime = $filter('date')(param.startTime, 'yyyy-MM-dd');
      param.endTime = $filter('date')(param.endTime, 'yyyy-MM-dd');
      //页面标题显示方式
      if (param.dimension === 't') {
        that.dimensionType = 't';
        if (param.startTime === param.endTime) {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + ' 流失用户数量统计';
          that.tabTitle = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + ' 流失用户数量统计';
        } else {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日') + ' 流失用户数量统计';
          that.tabTitle =$filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日') + ' 流失用户数量统计';
        }
      } else if (param.dimension === 'p') {
        that.dimensionType = 'p';
        if (param.startTime === param.endTime) {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + ' 各省流失用户占比';
          that.tabTitle = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + ' 各省流失用户数量统计';
        } else {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日') + ' 各省流失用户占比';
          that.tabTitle =$filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日') + ' 各省流失用户数量统计';
        }
      } else {
        that.dimensionType = 'b';
        if (param.startTime === param.endTime) {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + ' 各业务线流失用户占比';
          that.tabTitle = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + ' 各业务线流失用户数量统计';
        } else {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日') + ' 各业务线流失用户占比';
          that.tabTitle =$filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日') + ' 各业务线流失用户数量统计';
        }

      }
      CoreLoading.setState(true);
      $http.post('/sas/analysisUserBehavior/userChurnRate/queryChurnNum', param)
        .then(function (res) {
          that.showSearchPanel = false;   //收缩查询面板
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            dataList = res.data.data;
            that.arrow = false;
            that.changeViewType();  //默认显示折线图表
            that.showIcon = true; //显示表格和折线图标
          } else {
            that.PageDisplayStyle();
            CoreService.dialog('查询无数据');
            that.arrow = true;
          }
          CoreLoading.setState(false);
        });
    };

    //初始化折线图数据
    function initChart() {
      var option = {
        animation:false,
        tooltip: {
          trigger: 'item',
          formatter: function (param) {
            return param.name + '<br/>' + param.seriesName + ': ' + param.value + '个';
          }
        },
      };
      if (that.params.dimension === 't') {
        that.showPie = false;
        chart = echarts.init(document.getElementById('chartByDate'));
        var x = [];
        for (var i = 0; i <= dayCount; i++) {
          var b = (that.params.startTime / 1000 + 86400 * i) * 1000;
          var time = ($filter('date')(b, 'yyyy/MM/dd'));
          x.push(time);
        }
        ;
        option.animation = false;
        option.grid = {x: '104', x2: '128'};
        option.title={text:that.tabTitle,x:'center',textStyle:{fontSize:17}},
        option.legend = {data: ['流失用户数量'], x: 'right', y: 'center', orient: 'vertical'};
        option.xAxis = [{type: 'category', data: [], splitLine: {show: false}}];
        option.yAxis = [{name: '流失用户数量（个）', type: 'value', axisLabel: {formatter: '{value}'}}];
        option.series = [{name: '流失用户数量', type: 'bar', data: []}];
        var churnNumber =[];
        var time =[];
        angular.forEach(x, function (obj) {
          angular.forEach(dataList, function (data) {
            if (data.time === obj) {
              churnNumber = data.churnNumber;
              time = data.time;
              option.xAxis[0].data.push(time);
              option.series[0].data.push(churnNumber);
            }
          });

        });
        chart.setOption(option);
      } else {
        that.showPie = true;
        pieByPro_Bl = echarts.init(document.getElementById('pieByPro_Bl'));
        chartByPro_Bl = echarts.init(document.getElementById('chartByPro_Bl'));
        var pieOption = angular.copy(option);
        var barOption = angular.copy(option);
        var x = [];
        var attrName = '';
        if (that.params.dimension === 'p') {
          angular.forEach(dataList, function (data) {
            x.push(data.provinceCodeName);
          });
          attrName = 'provinceCodeName';
        } else {
          angular.forEach(dataList, function (data) {
            x.push(data.businessLineName);
          });
          attrName = 'businessLineName';
        }
        option.animation = false;
        pieOption.tooltip = {
          trigger: 'item',
          formatter: function (param) {
            return param.name + '<br/>' + param.seriesName + ': ' + param.value + '%';
          }
        };
        pieOption.title={text:that.title,x:'center',textStyle:{fontSize:17}},
        pieOption.series = [{name: '流失用户占比', type: 'pie', radius: '65%', center: ['50%', '55%'], data: []}];
        barOption.title={text:that.tabTitle,x:'center',textStyle:{fontSize:17}},
        barOption.grid = {x: '104', x2: '128'};
        barOption.xAxis = [{type: 'category', data: x, splitLine: {show: false}}];
        barOption.yAxis = [{name: '流失用户数量（个）', type: 'value', axisLabel: {formatter: '{value}'}}];
        barOption.legend = {data: ['流失用户数量'], x: 'right', y: 'center', orient: 'vertical'};
        barOption.series = [{name: '流失用户数量', type: 'bar', data: []}];
        angular.forEach(x, function (obj) {
          var churnNumP = '';
          var churnNumb = 0;
          angular.forEach(dataList, function (data) {
            if (data[attrName] === obj) {
              churnNumP = data.churnRate;
              churnNumb += data.churnNumber;
            }
          });
          pieOption.series[0].data.push({value: churnNumP.replace('%', ''), name: obj});
          barOption.series[0].data.push(churnNumb);
        });
        pieByPro_Bl.setOption(pieOption);
        chartByPro_Bl.setOption(barOption);

      }
      $timeout(function(){
        that.sendData=onSubmit();   //导出的图表生成
      },1000);
      // console.log(that.sendData);
    }

    /**初始化表格*/
    function initTable() {
      var list = [];
      if (that.params.dimension === 't') {
        var x = [];
        for (var i = 0; i <= dayCount; i++) {
          var b = (that.params.startTime / 1000 + 86400 * i) * 1000;
          var time = ($filter('date')(b, 'yyyy/MM/dd'));
          x.push(time);
        }
        ;
        /*angular.forEach(dataList, function (data) {
         x.push(data.time)
         });*/

        angular.forEach(x, function (obj) {
          angular.forEach(dataList, function (data) {
            if (data.time === obj) {
              list.push({date: obj, value: data.churnNumber});
            }
          });
          return list;
        });
      } else {
        var x = [], attrName = '';

        if (that.params.dimension === 'p') {
          x = [];
          angular.forEach(dataList, function (data) {
            x.push(data.provinceCodeName);
          });
          attrName = 'provinceCodeName';
        } else {
          x = [];
          angular.forEach(dataList, function (data) {
            x.push(data.businessLineName);
          });
          attrName = 'businessLineName';
        }
        angular.forEach(x, function (obj) {
          var churnNumTotal = 0;
          var churnRate = '0%';
          var ProCode = "";
          angular.forEach(dataList, function (data) {
            if (data[attrName] === obj) {
              churnNumTotal += data.churnNumber;
              ProCode = data.provinceCode;
              churnRate = data.churnRate ? data.churnRate : '0%';
            }
          });
          list.push({date: dataList[0].time, value: churnNumTotal, name: obj,code:ProCode, rate: churnRate});
        });

      }
      that.alaDataList = list;

    }

    //查询无数据时页面的样式
    this.PageDisplayStyle = function () {
      that.tabTitle=null;
      that.title=null;
      that.showSearchPanel = true;   //显示查询面板
      that.showIcon = false;  //隐藏表格和折线图标
      dataList = [];  //数据清空
      chart && chart.clear();  //折线图表数据清空
      pieByPro_Bl && pieByPro_Bl.clear();
      chartByPro_Bl && chartByPro_Bl.clear();
    };

    //控制显示折线或者表格
    this.changeViewType = function (type) {
      initChart();
      var ta = document.getElementById('ta');
      var cha = document.getElementById('cha');
      that.viewType = type || that.viewType;
      if (that.viewType === 'chart') {
        initChart();
        ta.style.backgroundColor = "";
        cha.style.backgroundColor = "#2196F3";
      } else if (that.viewType === 'table') {
        ta.style.backgroundColor = "#2196F3";
        cha.style.backgroundColor = "";
        initTable();
      }

    };

    /**导出excel*/
    function onSubmit(){
      var base64 = [];
      if (param.dimension === 't') {
        var c = chart.getDataURL('png').split(',')[1];
        base64.push(c);
      } else {
        var pie = pieByPro_Bl.getDataURL('png').split(',')[1];
        var pt = chartByPro_Bl.getDataURL('png').split(',')[1];
        base64.push(pie);
        base64.push(pt);
      }
      var data = {
        startTime: $filter('date')(that.params.startTime, 'yyyy-MM-dd'),
        endTime: $filter('date')(that.params.endTime, 'yyyy-MM-dd'),
        title: that.tabTitle,
        dimension: param.dimension,
        base64s: base64,
      };

      return JSON.stringify(data);
    };
  }

  dUserChurnAnalysisService.$inject = ['$http', '$filter', 'CoreService', '$timeout', 'CoreLoading'];
})();